package com.knife.file.domain.service.factory;

import com.knife.common.constants.BaseConstants;
import com.knife.common.exception.CommonException;
import com.knife.common.utils.KnifeEncryptionUtils;
import com.knife.common.utils.KnifeSpringUtil;
import com.knife.file.domain.entity.KnifeStorageConfig;
import com.knife.file.domain.service.KnifeFileService;
import com.knife.file.domain.service.KnifeStoreCreator;
import com.knife.file.domain.service.KnifeStoreService;
import com.knife.file.infra.cache.KnifeStorageConfigCache;
import com.knife.file.infra.mapper.KnifeFileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;

/**
 * 文件上传下载工厂，用于创建{@link KnifeStoreService}
 *
 * @author： 76875
 * @date： 2022/4/6 星期三 18:55
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Component
public class KnifeStoreFactory {

    @Autowired
    private KnifeFileInfoMapper knifeFileInfoMapper;
    @Autowired
    private KnifeStorageConfigCache knifeStorageConfigCache;

    public static String encrypt(String value) {
        return !StringUtils.hasText(value) ? value : KnifeEncryptionUtils.AES.encrypt(value, getSecurityKey());
    }

    public static String decrypt(String value) {
        return !StringUtils.hasText(value) ? value : KnifeEncryptionUtils.AES.decrypt(value, getSecurityKey());
    }

    private static String getSecurityKey() {
        return "hh76HeVNWJIxEnjMxeeAD1KWXHxzHJ54";
    }


    public KnifeStoreService build(Long tenantId, String storageCode) {
        // 获取当前租户配置信息
        KnifeStorageConfig storageConfig;
        KnifeStorageConfig condition = new KnifeStorageConfig();
        condition.setTenantId(tenantId);
        condition.setDefaultFlag(BaseConstants.Digital.ONE);
        condition.setStorageCode(storageCode);
        storageConfig = knifeStorageConfigCache.getValue(condition);
        // 解密密钥
        storageConfig.setAccessKeySecret(decrypt(storageConfig.getAccessKeySecret()));
        Map<String, KnifeStoreCreator> creatorMap = KnifeSpringUtil.getApplicationContext().getBeansOfType(KnifeStoreCreator.class);
        KnifeStoreCreator knifeStoreCreator = null;
        for (Map.Entry<String, KnifeStoreCreator> entry : creatorMap.entrySet()) {
            if (Objects.equals(entry.getValue().storeType(), storageConfig.getStorageType())) {
                knifeStoreCreator = entry.getValue();
                break;
            }
        }
        if (Objects.isNull(knifeStoreCreator)) {
            throw new CommonException("未配置文件上传服务");
        }
        KnifeFileService fileService = knifeStoreCreator.getFileService().init(storageConfig);
        return new KnifeStoreService(fileService, storageConfig, knifeFileInfoMapper);
    }
}
